package com.hckjsec.cloud.service;

import com.hckjsec.cloud.domain.*;
import com.hckjsec.cloud.domain.verification.VerificationLoginView;
import com.hckjsec.cloud.domain.view.CheckView;
import com.hckjsec.common.aspose.AsposeWord;
import com.hckjsec.common.config.*;
import com.hckjsec.common.core.redis.SerialNumberUtils;
import com.hckjsec.common.enums.NumbereEnum;
import com.hckjsec.common.enums.SysFileTypeEnum;
import com.hckjsec.common.utils.DateUtils;
import com.hckjsec.common.utils.DetectAuthUtil;
import com.hckjsec.common.utils.StringUtils;
import com.hckjsec.common.utils.file.FileUploadUtils;
import com.hckjsec.common.utils.sign.Base64Converter;
import com.hckjsec.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WxAsyncService {
    @Autowired
    private IAppletsBusinessVerificationService appletsBusinessVerificationService;
    @Autowired
    private IAppletsBusinessVideoUserService appletsBusinessVideoUserService;
    @Autowired
    private IAppletsBusinessVideoSignService appletsBusinessVideoSignService;
    @Autowired
    private IAppletsBusinessVideoSigncoorService appletsBusinessVideoSigncoorService;
    @Async
    public void getDetectVideoAuthInfo(String type, Long configid, Long deptid, String biztoken, CheckView checkView, String jgmc, AppletsApplicantUser appletsApplicantUser, WxVideoCallView wxVideoCallView) throws Exception {   //远程视频 生成活体报告
        try {
            Map<String,String> DocHt = new HashMap<>();
            DetectAuthLivingView detectAuthLivingView = new DetectAuthLivingView(checkView.getRuleId(),biztoken);
            DetectAuthResultView result = DetectAuthUtil.getVideoInfoRequest(checkView.getSecretId(),checkView.getSecretKey(),checkView.getRegion(),detectAuthLivingView);
            AppletsBusinessVerification appletsBusinessVerification = new AppletsBusinessVerification();
            appletsBusinessVerification.setBiztoken(biztoken);
            String verNumber= SerialNumberUtils.getSerialNumber(NumbereEnum.SYS_APPLETS_VERIFICATION_NUMBER);
            DocHt.put("hybh",verNumber);
            DocHt.put("jgmc",jgmc);
            appletsBusinessVerification.setVernumber(verNumber);
            appletsBusinessVerification.setVertype(type);
            appletsBusinessVerification.setConfigId(configid);
            appletsBusinessVerification.setDeptId(deptid);
            DetectAuthResultTextView twxtView = result.getText();
            appletsBusinessVerification.setName(twxtView.getName());
            DocHt.put("xm",twxtView.getName());
            appletsBusinessVerification.setIdcard(twxtView.getEdCard());
            DocHt.put("zjhm",twxtView.getEdCard());
            appletsBusinessVerification.setSim(twxtView.getSim());
            DocHt.put("hyfz",twxtView.getSim());
            String jg="成功";
            String errCode="0";
            if (!StringUtils.isHcNull(twxtView.getErrCode(), "").equals("0")) {
                errCode="1";
                jg="失败";
            }
            DocHt.put("hyjg",jg);
            DocHt.put("hysj", DateUtils.getTime());
            appletsBusinessVerification.setCode(errCode);
            DetectAuthResultIdCardView idCardView = result.getIdCardData();
            String xb=appletsApplicantUser.getGender().trim();
            if ("1".equals(xb)){
                DocHt.put("xb","男");
            }else{
                DocHt.put("xb","女");
            }
            DocHt.put("csrq",appletsApplicantUser.getBorntime());
            DocHt.put("zz",appletsApplicantUser.getCertificatesaddr());
            //现场照片
            DetectAuthResultBestFrameView bestFrame=result.getBestFrame();
            FileInfoView OcrBestFrameFileInfo = FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_IMG_PNG.getKey());;
            Base64Converter.generateFile(bestFrame.getBestFrame(),OcrBestFrameFileInfo.getPathFileName());
            appletsBusinessVerification.setBestframe(OcrBestFrameFileInfo.getFilePath());
            List<String>  absolutelyPath = new ArrayList<>();
            List<String>  relativePath = new ArrayList<>();
            List<String> bestFrames = result.getBestFrame().getBestFrames();
            bestFrames.forEach(kv->{
                FileInfoView  fileInfo = FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_IMG_PNG.getKey());
                boolean flag = Base64Converter.generateFile(kv,fileInfo.getPathFileName());
                if (flag){
                    absolutelyPath.add(fileInfo.getPathFileName());
                    relativePath.add(fileInfo.getFilePath());
                }
            });
            String ywslj=JeeThinkConfig.getProfile()+"/"+"verification"+"/"+"htbgvideo.doc";
            FileInfoView DocFileInfo= FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_DOCUMENT_DOC.getKey());
            String newdoclj=DocFileInfo.getPathFileName();
            AsposeWord.generateReportVideo(ywslj, newdoclj, DocHt, absolutelyPath);
            appletsBusinessVerificationService.insertAppletsBusinessVerification(appletsBusinessVerification);
            //转换成pdf
            FileInfoView PdfFileInfo= FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_DOCUMENT_PDF.getKey());
            String newpdflj=PdfFileInfo.getPathFileName();
            boolean flag=AsposeWord.word2pdf(newdoclj,newpdflj);
            if (flag){
                String uuid= IdUtils.simpleUUID();
                AppletsBusinessVideoUser appletsBusinessVideoUser=appletsBusinessVideoUserService.selectAppletsBusinessVideoUserById(Long.valueOf(wxVideoCallView.getSid()));
                AppletsBusinessVideoSign appletsBusinessVideoSign= new AppletsBusinessVideoSign();
                appletsBusinessVideoSign.setUuid(uuid);
                appletsBusinessVideoSign.setConfigId(configid);
                appletsBusinessVideoSign.setDeptId(deptid);
                appletsBusinessVideoSign.setVideoid(wxVideoCallView.getVideoId());
                appletsBusinessVideoSign.setFilename("活体报告-"+twxtView.getName());
                appletsBusinessVideoSign.setFilepath(PdfFileInfo.getFilePath());
                appletsBusinessVideoSign.setPdfwidth("1190");
                appletsBusinessVideoSign.setPdfheight("1683");
                appletsBusinessVideoSign.setContractid("-1");
                appletsBusinessVideoSign.setDocid("-1");
                appletsBusinessVideoSign.setState("0");
                appletsBusinessVideoSignService.insertAppletsBusinessVideoSign(appletsBusinessVideoSign);
                AppletsBusinessVideoSigncoor appletsBusinessVideoSigncoor = new AppletsBusinessVideoSigncoor();
                appletsBusinessVideoSigncoor.setUuid(uuid);
                appletsBusinessVideoSigncoor.setConfigId(configid);
                appletsBusinessVideoSigncoor.setDeptId(deptid);
                appletsBusinessVideoSigncoor.setUserid(appletsBusinessVideoUser.getId());
                appletsBusinessVideoSigncoor.setSignuserid(appletsBusinessVideoUser.getSignuserid());
                appletsBusinessVideoSigncoor.setSignusername(appletsBusinessVideoUser.getSignusername());
                appletsBusinessVideoSigncoor.setState("0");
                appletsBusinessVideoSigncoor.setDocwidth("165");
                appletsBusinessVideoSigncoor.setDocheight("70");
                appletsBusinessVideoSigncoor.setDoctop("1260");
                appletsBusinessVideoSigncoor.setDocleft("806");
                appletsBusinessVideoSigncoor.setDocangle("0");
                appletsBusinessVideoSigncoor.setDocscalex("1");
                appletsBusinessVideoSigncoor.setDocscaley("1");
                appletsBusinessVideoSigncoor.setDocpagenum("1");
                appletsBusinessVideoSigncoorService.insertAppletsBusinessVideoSigncoor(appletsBusinessVideoSigncoor);
                appletsBusinessVideoUser.setIsliving(verNumber);
                appletsBusinessVideoUserService.updateAppletsBusinessVideoUser(appletsBusinessVideoUser);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Async
    public void getDetectVerificationAuthInfo(String type, Long configid, Long deptid, String biztoken, CheckView checkView, VerificationLoginView verificationLoginView) throws Exception {   //远程视频 生成活体报告
        try {
            Map<String,String> DocHt = new HashMap<>();
            DetectAuthLivingView detectAuthLivingView = new DetectAuthLivingView(checkView.getRuleId(),biztoken);
            DetectAuthResultView result = DetectAuthUtil.getVideoInfoRequest(checkView.getSecretId(),checkView.getSecretKey(),checkView.getRegion(),detectAuthLivingView);
            AppletsBusinessVerification appletsBusinessVerification = new AppletsBusinessVerification();
            appletsBusinessVerification.setBiztoken(biztoken);
            String verNumber= SerialNumberUtils.getSerialNumber(NumbereEnum.SYS_APPLETS_VERIFICATION_NUMBER);
            DocHt.put("hybh",verNumber);
            DocHt.put("jgmc",verificationLoginView.getDeptName());
            appletsBusinessVerification.setVernumber(verNumber);
            appletsBusinessVerification.setVertype(type);
            appletsBusinessVerification.setConfigId(configid);
            appletsBusinessVerification.setDeptId(deptid);
            appletsBusinessVerification.setUserid(verificationLoginView.getUserId());
            appletsBusinessVerification.setUsername(verificationLoginView.getLoginname());
            DetectAuthResultTextView twxtView = result.getText();
            appletsBusinessVerification.setName(twxtView.getName());
            DocHt.put("xm",twxtView.getName());
            appletsBusinessVerification.setGender(twxtView.getOcrGender());
            DocHt.put("xb",twxtView.getOcrGender());
            appletsBusinessVerification.setNation(twxtView.getOcrNation());
            appletsBusinessVerification.setBirth(twxtView.getOcrBirth());
            DocHt.put("csrq",twxtView.getOcrBirth());
            appletsBusinessVerification.setIdcard(twxtView.getEdCard());
            DocHt.put("zjhm",twxtView.getEdCard());
            appletsBusinessVerification.setAddress(twxtView.getOcrAddress());
            DocHt.put("zz",twxtView.getOcrAddress());
            appletsBusinessVerification.setAuthority(twxtView.getOcrAuthority());
            appletsBusinessVerification.setValiddate(twxtView.getOcrValidDate());
            appletsBusinessVerification.setSim(twxtView.getSim());
            DocHt.put("hyfz",twxtView.getSim());
            String jg="成功";
            String errCode="0";
            if (!StringUtils.isHcNull(twxtView.getErrCode(), "").equals("0")) {
                errCode="1";
                jg="失败";
            }
            DocHt.put("hyjg",jg);
            DocHt.put("hysj", DateUtils.getTime());
            appletsBusinessVerification.setCode(errCode);
            DetectAuthResultIdCardView idCardView = result.getIdCardData();
            //正面图片
            FileInfoView OcrFrontFileInfo= FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_IMG_PNG.getKey());
            if (StringUtils.isEmpty(idCardView.getProcessedFrontImage())){
                 Base64Converter.generateFile(idCardView.getOcrFront(),OcrFrontFileInfo.getPathFileName());
            }else{
                 Base64Converter.generateFile(idCardView.getProcessedFrontImage(),OcrFrontFileInfo.getPathFileName());
            }
            DocHt.put("zmImg",OcrFrontFileInfo.getPathFileName());
            appletsBusinessVerification.setOcrfront(OcrFrontFileInfo.getFilePath());
            //背面照
            FileInfoView OcrBackFileInfo = FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_IMG_PNG.getKey());
            if (StringUtils.isEmpty(idCardView.getProcessedBackImage())){
                 Base64Converter.generateFile(idCardView.getOcrBack(),OcrBackFileInfo.getPathFileName());
            }else{
                 Base64Converter.generateFile(idCardView.getProcessedBackImage(),OcrBackFileInfo.getPathFileName());
            }
            appletsBusinessVerification.setOcrback(OcrBackFileInfo.getFilePath());
            List<String>  absolutelyPath = new ArrayList<>();
            List<String>  relativePath = new ArrayList<>();
            List<String> bestFrames = result.getBestFrame().getBestFrames();
            bestFrames.forEach(kv->{
                FileInfoView  fileInfo = FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_IMG_PNG.getKey());
                boolean flag = Base64Converter.generateFile(kv,fileInfo.getPathFileName());
                if (flag){
                    absolutelyPath.add(fileInfo.getPathFileName());
                    relativePath.add(fileInfo.getFilePath());
                }
            });

            FileInfoView  videoFileInfo = FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_VIDEO_MP4.getKey());
            Base64Converter.generateFile(result.getVideoData(),videoFileInfo.getPathFileName());
            appletsBusinessVerification.setVideo(videoFileInfo.getFilePath());
            //现场照片
            String ywslj=JeeThinkConfig.getProfile()+"/"+"verification"+"/"+"htbg.doc";
            FileInfoView DocFileInfo= FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_DOCUMENT_DOC.getKey());
            String newdoclj=DocFileInfo.getPathFileName();
            boolean docmsg= AsposeWord.generateReportVerification(ywslj, newdoclj, DocHt,absolutelyPath);
            if (docmsg){
                FileInfoView PdfFileInfo= FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_DOCUMENT_PDF.getKey());
                String newpdflj=PdfFileInfo.getPathFileName();
                AsposeWord.word2pdf(newdoclj,newpdflj);
                appletsBusinessVerification.setReportdoc(PdfFileInfo.getFilePath());
                FileInfoView  imgfileInfo = FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_IMG_PNG.getKey());
                String newimglj=imgfileInfo.getPathFileName();
                AsposeWord.generateReportToPng(newdoclj,newimglj);
                appletsBusinessVerification.setReportimg(imgfileInfo.getFilePath());
                appletsBusinessVerification.setBestframe(StringUtils.join(relativePath.toArray(),";"));
                appletsBusinessVerificationService.insertAppletsBusinessVerification(appletsBusinessVerification);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
